'use strict'

const path = require('path')
const fs = require('fs')

function isObject(o) {
  return Object.prototype.toString.call(o) === '[object Object]'
}

function spinnerStart(msg, spinnerString = '|/-\\') {
  const Spinner = require('cli-spinner').Spinner

  const spinner = new Spinner(msg + '%s')
  spinner.setSpinnerString(spinnerString)
  spinner.start()
  return spinner
}

function sleep(timeout = 1000) {
  return new Promise(resolve => setTimeout(resolve, timeout)) // 让当前进程中止
}

function spawnExec(command, args, options) {
  const win32 = process.platform === 'win32'
  const cmd = win32 ? 'cmd' : command
  const cmdArgs = win32 ? ['/c'].concat(command, args) : args // /c 表示静默执行
  return require('child_process').spawn(cmd, cmdArgs, options || {})
}

function spawnExecSync(command, args, options) {
  return new Promise((resolve, reject) => {
    const p = spawnExec(command, args, options)
    p.on('error', e => {
      reject(e)
    })
    p.on('exit', c => {
      resolve(c)
    })
  })
}

// path兼容处理
function formatPath(p) {
  if (p && typeof p === 'string') {
    const sep = path.sep // 文件路径分隔符
    if (sep === '/') {
      return p
    } else {
      // window下是 '\', 需要转换
      return p.replace(/\\/g, '/')
    }
  }
  return p
}

function readFile(path, options = {}) {
  if (fs.existsSync(path)) {
    const buffer = fs.readFileSync(path)
    if (buffer) {
      if (options.toJson) {
        // 若有要求转换成json
        return buffer.toJSON()
      } else {
        return buffer.toString()
      }
    }
  }
  return null
}

function writeFile(path, data, { rewrite = true } = {}) {
  if (fs.existsSync(path)) {
    if (rewrite) {
      fs.writeFileSync(path, data)
      return true
    }
    return false
  } else {
    fs.writeFileSync(path, data)
    return true
  }
}

module.exports = {
  formatPath,
  isObject,
  spinnerStart,
  sleep,
  spawnExec,
  spawnExecSync,
  readFile,
  writeFile,
}
